﻿
Namespace AnalysisTechniques
    Public Class AutoTrend_old

#Region "AnalysisTechnique Inherited Code"
        Inherits AnalysisTechnique
        Public Sub New(ByVal chart As Chart)
            MyBase.New(chart) ' Call the base class constructor.
            Description = "Main AutoTrend_old analysis technique."
            Name = "AutoTrend_oldV2"
            If chart IsNot Nothing Then AddHandler chart.ChartKeyDown, AddressOf KeyPress
        End Sub
#End Region

        Const MANY_OPTIONS = True

        Private bcLengths As New List(Of Double)
        Private prevRV As Decimal = -1
        Protected Sub KeyPress(ByVal sender As Object, ByVal e As KeyEventArgs)
            If Chart IsNot Nothing AndAlso IsEnabled Then
                Dim key As Key
                If e.SystemKey = key.None Then
                    key = e.Key
                Else
                    key = e.SystemKey
                End If
                If Keyboard.Modifiers = ModifierKeys.None Then
                    If key = IncrementRVUpFineAmount Then
                        RV += FineRVIncrementValue
                        Chart.ReApplyAnalysisTechnique(Me)
                    ElseIf key = IncrementRVDownFineAmount And RV >= FineRVIncrementValue Then
                        RV -= FineRVIncrementValue
                        Chart.ReApplyAnalysisTechnique(Me)
                    ElseIf key = IncrementRVUpCoarseAmount Then
                        RV += CoarseRVIncrementValue
                        Chart.ReApplyAnalysisTechnique(Me)
                    ElseIf key = IncrementRVDownCoarseAmount And RV >= CoarseRVIncrementValue Then
                        RV -= CoarseRVIncrementValue
                        Chart.ReApplyAnalysisTechnique(Me)
                    ElseIf key = SetRVTo2xRange Then
                        RVBase()
                    ElseIf key = SetRVToNextBCLength Then
                        RVUp()
                    ElseIf key = SetRVToPreviousBCLength Then
                        RVDown()
                    ElseIf key = ToggleMergedChannelsColoring Then
                        If ChannelMode = ChannelModeType.Merged Then
                            ChannelMode = ChannelModeType.Unmerged
                        Else
                            ChannelMode = ChannelModeType.Merged
                        End If

                        Chart.ReApplyAnalysisTechnique(Me)
                    End If
                End If
            End If
        End Sub
#Region "Commands"
        Friend Sub PlusMinMove()
            RV += Chart.GetMinTick
            Chart.ReApplyAnalysisTechnique(Me)
        End Sub
        Friend Sub MinusMinMove()
            RV -= Chart.GetMinTick
            Chart.ReApplyAnalysisTechnique(Me)
        End Sub
        Friend Sub RVDown()
            If bcLengths.Count > 0 Then
                RV = bcLengths(bcLengths.Count - 1)
                bcLengths.RemoveAt(bcLengths.Count - 1)
                Chart.ReApplyAnalysisTechnique(Me)
            End If
        End Sub
        Friend Function GetRVBase() As Decimal
            If Not Chart.Settings("IsSlaveChart").Value Then
                Return Chart.Settings("RangeValue").Value * 2
            End If
            Return 0
        End Function
        Friend Sub RVBase()
            If Not Chart.Settings("IsSlaveChart").Value Then
                If RV = GetRVBase() Then
                    If prevRV <> -1 Then
                        RV = prevRV
                        Chart.ReApplyAnalysisTechnique(Me)
                    End If
                Else
                    prevRV = RV
                    RV = GetRVBase()
                    Chart.ReApplyAnalysisTechnique(Me)
                End If
            End If
        End Sub
        Friend Sub RVUp()
            Dim shortest As Decimal = Decimal.MaxValue
            Dim nextShortest As Decimal = Decimal.MaxValue
            For Each swing In swings
                If Abs(swing.StartPrice - swing.EndPrice) < shortest And Abs(swing.StartPrice - swing.EndPrice) >= RV Then
                    shortest = Round(Abs(swing.StartPrice - swing.EndPrice), 3)
                End If
            Next
            If RV <> shortest Then
                bcLengths.Add(RV)
                RV = shortest
                Chart.ReApplyAnalysisTechnique(Me)
                'MsgBox("")
            Else
                For Each swing In swings
                    Dim height As Decimal = Abs(swing.StartPrice - swing.EndPrice)
                    If height > shortest Then
                        nextShortest = Min(nextShortest, height)
                    End If
                Next
                bcLengths.Add(RV)
                RV = nextShortest
                Chart.ReApplyAnalysisTechnique(Me)
            End If
            'For i = channels.Count - 1 To 0 Step -1
            '    Dim channelLine As Channel = channels(i)
            '    If channelLine.IsConfirmed And Not channelLine.IsCancelled Then
            '        bcLengths.Add(RV)
            '        If RV = Round(Abs(CurrentSwing.StartPrice - CurrentSwing.EndPrice), 5) Then
            '            RV = Round(Abs(CurrentSwing.StartPrice - CurrentSwing.EndPrice) + Chart.GetMinTick, 5)
            '        ElseIf Round(Abs(CurrentSwing.StartPrice - CurrentSwing.EndPrice), 5) < Round(Abs(channelLine.BCSwingLine.EndPoint.Y - channelLine.BCSwingLine.StartPoint.Y), 5) Then
            '            RV = Round(Abs(CurrentSwing.StartPrice - CurrentSwing.EndPrice), 5)
            '        ElseIf RV = Round(Abs(channelLine.BCSwingLine.EndPoint.Y - channelLine.BCSwingLine.StartPoint.Y), 5) Then
            '            RV = Round(Abs(channelLine.BCSwingLine.EndPoint.Y - channelLine.BCSwingLine.StartPoint.Y) + Chart.GetMinTick, 5)
            '        Else
            '            RV = Round(Abs((channelLine.BCSwingLine.EndPoint.Y - channelLine.BCSwingLine.StartPoint.Y)), 5)
            '        End If
            '        Chart.ReApplyAnalysisTechnique(Me)
            '        Exit For
            '    End If
            'Next
        End Sub

        Friend Sub ApplyRV(value As Decimal)
            If value <> 0 Then
                If RV <> value Then
                    RV = value
                    Chart.ReApplyAnalysisTechnique(Me)
                End If
            End If
        End Sub
        Friend Sub ChannelMerge()
            Dim prev As ChannelModeType = ChannelMode
            ChannelMode = ChannelModeType.Merged
            If prev <> ChannelMode Then Chart.ReApplyAnalysisTechnique(Me)
        End Sub
        Friend Sub ChannelUnmerge()
            Dim prev As ChannelModeType = ChannelMode
            ChannelMode = ChannelModeType.Unmerged
            If prev <> ChannelMode Then Chart.ReApplyAnalysisTechnique(Me)
        End Sub
        Friend Sub ChannelSetToBase()
            Dim prev As ChannelModeType = ChannelMode
            ChannelMode = ChannelModeType.SetToBase
            If prev <> ChannelMode Then Chart.ReApplyAnalysisTechnique(Me)
        End Sub
#End Region

#Region "Types"
        Protected Class Swing
            Protected _tl As TrendLine
            Public ReadOnly Property TL As TrendLine
                Get
                    Return _tl
                End Get
            End Property
            Public Property Direction As Direction
            Public Sub New(ByVal tl As TrendLine, ByVal direction As Direction)
                _tl = tl
                StartBar = tl.StartPoint.X
                StartPrice = tl.StartPoint.Y
                EndBar = tl.EndPoint.X
                EndPrice = tl.EndPoint.Y
                Me.Direction = direction
            End Sub
            Public Property StartBar As Integer
                Get
                    Return TL.StartPoint.X
                End Get
                Set(ByVal value As Integer)
                    TL.StartPoint = New Point(value, TL.StartPoint.Y)
                End Set
            End Property
            Public Property StartPrice As Decimal
                Get
                    Return TL.StartPoint.Y
                End Get
                Set(ByVal value As Decimal)
                    TL.StartPoint = New Point(TL.StartPoint.X, value)
                End Set
            End Property
            Public Property EndBar As Integer
                Get
                    Return TL.EndPoint.X
                End Get
                Set(ByVal value As Integer)
                    TL.EndPoint = New Point(value, TL.EndPoint.Y)
                End Set
            End Property
            Public Property EndPrice As Decimal
                Get
                    Return TL.EndPoint.Y
                End Get
                Set(ByVal value As Decimal)
                    TL.EndPoint = New Point(TL.EndPoint.X, value)
                End Set
            End Property
            Public Shared Operator =(ByVal swing1 As Swing, ByVal swing2 As Swing) As Boolean
                Return swing1 Is swing2
            End Operator
            Public Shared Operator <>(ByVal swing1 As Swing, ByVal swing2 As Swing) As Boolean
                Return swing1 IsNot swing2
            End Operator
            Public Property ChannelLine As Channel
        End Class
        Protected Class Channel
            Public Sub New(ByVal tl As TrendLine)
                Me.TL = tl
            End Sub
            Public Property TL As TrendLine

            Public Property APoint As Point
            Public Property BPoint As Point
            Public Property CPoint As Point
            Public Property DPoint As Point

            Public Property Direction As Direction

            Public Property Swing As Swing

            Public Property BCSwingLine As TrendLine
            Public Property ABSwingLine As TrendLine
            Public Property CDSwingLine As TrendLine
            Public Property BCLengthText As Label
            Public Property TargetText As Label

            Public Property IsCancelled As Boolean
            Public Property IsConfirmed As Boolean
            Public Property IsCut As Boolean
            Public Property IsGapped As Boolean
            Public Property BCSwingLineRemoved As Boolean
            Public Property BCSwingMatched As Boolean
            Public Property CutBarNumber As Integer = -1
            Public Property IsBackedUp As Boolean
            Public Property IsPartiallyCut As Boolean

        End Class
        Protected Class SwingChannelLine
            Public Sub New(ByVal tl As TrendLine)
                tl = tl
            End Sub
            Public Property TL As TrendLine
            Public Property BCSwingLine As TrendLine
            Public Property IsActive As Boolean
            Public Property IsConfirmed As Boolean
            Public Property APoint As Point
            Public Property BPoint As Point
            Public Property CPoint As Point
        End Class
        Protected Structure GapMarker
            Public Property Line As TrendLine
            Public Property Swing As Swing
            Public Property State As GapMarkerState
        End Structure
        Public Enum GapMarkerState
            Inactive
            FollowsRVPoint
            FollowsExtension
        End Enum
        Public Enum Direction
            Up = -1
            Down = 0
        End Enum
        Private Enum SwingEvent
            None = -1
            NewSwing = 0
            Extension = 1
        End Enum

        Private Class PartiallyCutChannel
            Public Sub New(channel As Channel, swingNum As Integer)
                Me.Channel = channel
                Me.SwingNum = swingNum
            End Sub
            Public Channel As Channel
            Public SwingNum As Integer
        End Class
#End Region

#Region "Inputs"
        Private _rv As Decimal = 2
        Public ReadOnly Property RawRV As Decimal
            Get
                Return _rv
            End Get
        End Property
        <Input("The reversal value.")>
        Public Property RV As Decimal
            Get
                If ChannelMode = ChannelModeType.SetToBase Then
                    Return GetRVBase()
                Else
                    Return _rv
                End If
            End Get
            Set(value As Decimal)
                _rv = Round(value, 3)
                If Chart IsNot Nothing Then
                    'TODO:
                    'Chart.UpdateAutoTrendPad(Me)
                End If
            End Set
        End Property
        '<Input("The base RV.")> Public Property BaseRV As Decimal = 2
        '<Input("The reversal value for the swing channel.")>
        Public Property SwingRV As Decimal
        '<Input("The dollar equivalent of the symbol minimum move.")> Public Property SymbolPriceMinimumMove As Decimal = 25

        '<Input("The number of decimal places shown on all labels.")>
        Public Property DecimalPlaces As Integer = 2

        <Input("The RV text color.")>
        Public Property RVTextColor As Color = Colors.White
        <Input("The channel mode.")>
        Public Property ChannelMode As ChannelModeType = ChannelModeType.Merged

        <Input("The color for swing lines.", "Swing Lines")>
        Public Property NeutralSwingLineColor As Color = Colors.LightGray
        <Input("The color for swing lines during a down trend.")>
        Public Property ProjectionLineColor As Color = Colors.Fuchsia
        <Input("The color for swing lines during an up trend.")>
        Public Property UpTrendSwingLineColor As Color = ColorConverter.ConvertFromString("#FF00BF00")
        <Input("The color for swing lines during a down trend.")>
        Public Property DownTrendSwingLineColor As Color = ColorConverter.ConvertFromString("#FFBF0000")
        <Input("The color for swing length texts.")>
        Public Property SwingLengthTextColor As Color = Colors.Gray

        <Input("The visibility for swing lines.", "Visibility Switches")>
        Public Property SwingLinesVisible As Boolean = True
        <Input("The option to hide the last swing line.")>
        Public Property HideLastSwingLine As Boolean = True
        <Input("The visibility for swing length texts.")>
        Public Property SwingLengthTextsVisible As Boolean = True
        <Input("The visibility for the current swing channel line.")>
        Public Property CurrentSwingChannelLineVisible As Boolean = True
        <Input("The visibility for channel lines.")>
        Public Property ChannelLinesVisible As Boolean = True
        <Input("The option to hide all potential channel lines except the last one in each direction.")>
        Public Property ShowOnlyLastPotentialChannels As Boolean = True
        <Input("The option to hide all confirmed channel lines except the last one in each direction.")>
        Public Property ShowOnlyLastConfirmedChannels As Boolean = True
        <Input("The option to hide channels which start point is off the left side of the chart.")>
        Public Property ShowOnlyChannelsOnScreen As Boolean = True
        <Input("The option to highlight the last cut channel.")>
        Public Property HighlightLastCutChannel As Boolean = True
        <Input("The visibility for confirmed history channel lines.")>
        Public Property ConfirmedHistoryChannelLinesVisible As Boolean = False
        <Input("The visibility for potential history channel lines.")>
        Public Property PotentialHistoryChannelLinesVisible As Boolean = False
        <Input("The visibility for potential and confirmed history channel line parallels.")>
        Public Property HistoryChannelLineParallelsVisible As Boolean = False
        <Input("The visibility for BC length texts.")>
        Public Property BCLengthTextsVisible As Boolean = True
        <Input("The visibility for BC target texts.")>
        Public Property BCTargetTextsVisible As Boolean = True
        <Input("The color for up gap markers.", "Gap Markers")>
        Public Property UpGapMarkerColor As Color = Colors.LightGreen
        <Input("The color for down gap markers.")>
        Public Property DownGapMarkerColor As Color = Colors.Pink

        <Input("The color for potential up channel lines.", "Channel Lines")>
        Public Property PotentialUpChannelLineColor As Color = ColorConverter.ConvertFromString("#FF005000")
        <Input("The color for potential down channel lines.")>
        Public Property PotentialDownChannelLineColor As Color = ColorConverter.ConvertFromString("#FF550000")
        <Input("The color for confirmed up channel lines.")>
        Public Property ConfirmedUpChannelLineColor As Color = Colors.Lime
        <Input("The color for confirmed down channel lines.")>
        Public Property ConfirmedDownChannelLineColor As Color = Colors.Red
        <Input("The color for backed up confirmed up channel lines.")>
        Public Property BackedUpConfirmedUpChannelLineColor As Color = Colors.DarkGreen
        <Input("The color for backed up confirmed down channel lines.")>
        Public Property BackedUpConfirmedDownChannelLineColor As Color = Colors.DarkRed
        '        <Input("The color for backed up potential up channel lines.")>
        '        Public Property BackedUpPotentialUpChannelLineColor As Color = Colors.DarkMagenta

        '        <Input("The color for backed up potential down channel lines.")>
        '        Public Property BackedUpPotentialDownChannelLineColor As Color = Colors.DarkGoldenrod
        <Input("The color for potential up channel lines that have been hit.")>
        Public Property PotentialHistoryUpChannelLineColor As Color = ColorConverter.ConvertFromString("#FF404000")
        <Input("The color for potential down channel lines that have been hit.")>
        Public Property PotentialHistoryDownChannelLineColor As Color = ColorConverter.ConvertFromString("#FF002B55")
        <Input("The color for confirmed up channel lines that have been hit.")>
        Public Property ConfirmedHistoryUpChannelLineColor As Color = ColorConverter.ConvertFromString("#FF008500")
        <Input("The color for confirmed down channel lines that have been hit.")>
        Public Property ConfirmedHistoryDownChannelLineColor As Color = ColorConverter.ConvertFromString("#FFB40000")
        <Input("The color for gapped up channel lines.")>
        Public Property GappedUpChannelLineColor As Color = Colors.Purple
        <Input("The color for gapped down channel lines.")>
        Public Property GappedDownChannelLineColor As Color = Colors.Purple

        <Input("The option to enable or disable bar coloring.", "Bar Coloring")>
        Public Property ColorBars As Boolean = True
        <Input("The color for the bars during a neutral trend direction state.")>
        Public Property NeutralBarColor As Color = Colors.Gray
        <Input("The color for the bars during an up trend.")>
        Public Property UpTrendBarColor As Color = ColorConverter.ConvertFromString("#FF006A00")
        <Input("The color for the bars during a down trend.")>
        Public Property DownTrendBarColor As Color = ColorConverter.ConvertFromString("#FF6A0000")

        <Input("The fine adjustment for the RV.", "Hotkeys")> Public Property FineRVIncrementValue As Decimal = 0.5
        <Input("The course adjustment for the RV.")> Public Property CoarseRVIncrementValue As Decimal = 0.5
        <Input("The hotkey to increment the RV up the specified fine amount.")>
        Public Property IncrementRVUpFineAmount As Key = Key.None
        <Input("The hotkey to increment the RV down the specified fine amount.")>
        Public Property IncrementRVDownFineAmount As Key = Key.None
        <Input("The hotkey to increment the RV up the specified coarse amount.")>
        Public Property IncrementRVUpCoarseAmount As Key = Key.None
        <Input("The hotkey to increment the RV down the specified coarse amount.")>
        Public Property IncrementRVDownCoarseAmount As Key = Key.None
        <Input("The hotkey to toggle whether merged channels are colored.")>
        Public Property ToggleMergedChannelsColoring As Key = Key.None

        <Input()> Public Property SetRVTo2xRange As Key = Key.None
        '<Input()> Public Property SetRVTo3xRange As Key = Key.None
        <Input()> Public Property SetRVToNextBCLength As Key = Key.None
        <Input()> Public Property SetRVToPreviousBCLength As Key = Key.None

#End Region

        Public Overrides Property Name As String

        Private rvText As Label
        Private rvSecondaryText As Label
        Private rvProNewLine As TrendLine
        Private rvProExtLine As TrendLine

        Private currentGapMark As GapMarker

        Private barColorsDirty As Boolean

        Private swings As List(Of Swing)
        Private secondarySwings As List(Of Swing)
        Private channels As List(Of Channel)
        Private swingChannel As SwingChannelLine
        Private currentPartiallyCutChannel As PartiallyCutChannel

        'Private colorMergedChannels As Boolean = True
        Private swingCountGraphYPlacement As Decimal
        Private currentSwingCountGraphLine As TrendLine
        Public Enum ChannelModeType
            Merged
            Unmerged
            SetToBase
        End Enum
        'Private backupChannelLines As List(Of Channel)

        Private ReadOnly Property CurrentSwing As Swing
            Get
                Return swings(swings.Count - 1)
            End Get
        End Property
        Private ReadOnly Property CurrentSwing(barsBack As Integer) As Swing
            Get
                If swings.Count > barsBack Then
                    Return swings(swings.Count - barsBack - 1)
                Else
                    Return Nothing
                End If
            End Get
        End Property
        Private ReadOnly Property CurrentChannelLine As Channel
            Get
                If channels.Count > 0 Then
                    Return channels(channels.Count - 1)
                Else
                    Return Nothing
                End If
            End Get
        End Property


        Friend Overrides Sub OnCreate()
            MyBase.OnCreate()
            If Chart IsNot Nothing Then
                RV = Chart.Settings("RangeValue").Value * 2
                DecimalPlaces = 2
                FineRVIncrementValue = Chart.GetMinTick
                CoarseRVIncrementValue = Chart.GetMinTick * 5
            End If
        End Sub
        Public Overrides Sub Reset()
            MyBase.Reset()
            If (ColorBars Or barColorsDirty) And Chart.bars.Count > 1 Then
                BarColor(0, Chart.bars.Count - 1, Chart.Settings("Bar Color").Value, NeutralSwingLineColor)
                barColorsDirty = False
            End If
        End Sub
        Protected Overrides Sub Begin()
            'If doCalculate = True Then doCalculate = False
            channels = New List(Of Channel)
            swings = New List(Of Swing)
            swings.Add(New Swing(NewTrendLine(NeutralSwingLineColor, New Point(CurrentBar.Number, CurrentBar.Close), New Point(CurrentBar.Number, CurrentBar.Close), SwingLinesVisible), Direction.Down))
            currentSwingLengthText = NewLabel(GetDollarValue(Abs(swings(swings.Count - 1).StartPrice - swings(swings.Count - 1).EndPrice)), SwingLengthTextColor, New Point(swings(swings.Count - 1).EndBar, swings(swings.Count - 1).EndPrice), True)

            If ChannelMode = ChannelModeType.SetToBase Then
                secondarySwings = New List(Of Swing)
                secondarySwings.Add(New Swing(NewTrendLine(NeutralSwingLineColor, New Point(CurrentBar.Number, CurrentBar.Close), New Point(CurrentBar.Number, CurrentBar.Close), SwingLinesVisible), Direction.Down))
                secondarySwings(secondarySwings.Count - 1).TL.Pen.Thickness = 2.6
            End If


            rvText = NewLabel("", RVTextColor, New Point(0, 0), True)
            rvSecondaryText = NewLabel("", RVTextColor, New Point(0, 0), True)
            rvText.VerticalAlignment = LabelVerticalAlignment.Center
            rvText.HorizontalAlignment = LabelHorizontalAlignment.Left
            rvSecondaryText.VerticalAlignment = LabelVerticalAlignment.Center
            rvSecondaryText.HorizontalAlignment = LabelHorizontalAlignment.Left
            rvProNewLine = NewTrendLine(ProjectionLineColor, New Point(0, 0), New Point(0, 0), SwingLinesVisible)
            rvProExtLine = NewTrendLine(ProjectionLineColor, New Point(0, 0), New Point(0, 0), SwingLinesVisible)
            'rvProLine.Pen.DashStyle = TrendLineDashStyle

            swingChannel = New SwingChannelLine(NewTrendLine(NeutralSwingLineColor, New Point(0, 0), New Point(0, 0), True))

            currentPartiallyCutChannel = Nothing

            SwingRV = Chart.Settings("RangeValue").Value * 1.2
            swingCountGraphYPlacement = CurrentBar.Close + Chart.Settings("RangeValue").Value * 20
            currentSwingCountGraphLine = NewTrendLine(ConfirmedDownChannelLineColor, New Point(CurrentBar.Number, swingCountGraphYPlacement), New Point(CurrentBar.Number, swingCountGraphYPlacement))
            currentSwingCountGraphLine.Pen.Thickness = 10
        End Sub

        Dim curSwingEvent As SwingEvent = SwingEvent.None
        Dim swingDir As Direction
        Dim currentSwingLengthText As Label
        Protected Overrides Sub Main()
            If CurrentBar.Number = Round(Chart.Bounds.TopLeft.X) Then
                Reset()
                Begin()
            End If
            If CurrentBar.Number < Round(Chart.Bounds.TopLeft.X) Then Exit Sub
            Dim cs As Swing = CurrentSwing
            curSwingEvent = SwingEvent.None
            If CurrentBar.High - cs.EndPrice >= RV AndAlso CurrentBar.Number <> cs.EndBar AndAlso cs.Direction = Direction.Down Then
                'new swing up
                If HideLastSwingLine AndAlso swings.Count > 0 And SwingLinesVisible And ChannelMode <> ChannelModeType.SetToBase Then AddObjectToChart(swings(swings.Count - 1).TL)
                swings.Add(NewSwing(NeutralSwingLineColor, New Point(cs.EndBar, cs.EndPrice), New Point(CurrentBar.Number, CurrentBar.High), Not HideLastSwingLine And SwingLinesVisible And ChannelMode <> ChannelModeType.SetToBase, Direction.Up))
                If ChannelMode <> ChannelModeType.SetToBase Then
                    currentSwingLengthText = NewLabel(GetDollarValue(Abs(swings(swings.Count - 1).StartPrice - swings(swings.Count - 1).EndPrice)) & " ", SwingLengthTextColor, New Point(swings(swings.Count - 1).EndBar, swings(swings.Count - 1).EndPrice), False)
                    currentSwingLengthText.HorizontalAlignment = LabelHorizontalAlignment.Right
                    currentSwingLengthText.VerticalAlignment = LabelVerticalAlignment.Top
                    If SwingLengthTextsVisible Then AddObjectToChart(currentSwingLengthText)
                End If
                curSwingEvent = AutoTrend_old.SwingEvent.NewSwing
                swingDir = Direction.Up
            ElseIf cs.EndPrice - CurrentBar.Low >= RV AndAlso CurrentBar.Number <> cs.EndBar AndAlso cs.Direction = Direction.Up Then
                ' new swing down
                If HideLastSwingLine AndAlso swings.Count > 0 And SwingLinesVisible And ChannelMode <> ChannelModeType.SetToBase Then AddObjectToChart(swings(swings.Count - 1).TL)
                swings.Add(NewSwing(NeutralSwingLineColor, New Point(cs.EndBar, cs.EndPrice), New Point(CurrentBar.Number, CurrentBar.Low), Not HideLastSwingLine And SwingLinesVisible And ChannelMode <> ChannelModeType.SetToBase, Direction.Down))
                If ChannelMode <> ChannelModeType.SetToBase Then
                    currentSwingLengthText = NewLabel(GetDollarValue(Abs(swings(swings.Count - 1).StartPrice - swings(swings.Count - 1).EndPrice)) & " ", SwingLengthTextColor, New Point(swings(swings.Count - 1).EndBar, swings(swings.Count - 1).EndPrice), False)
                    currentSwingLengthText.HorizontalAlignment = LabelHorizontalAlignment.Right
                    currentSwingLengthText.VerticalAlignment = LabelVerticalAlignment.Bottom
                    If SwingLengthTextsVisible Then AddObjectToChart(currentSwingLengthText)
                End If
                curSwingEvent = AutoTrend_old.SwingEvent.NewSwing
                swingDir = Direction.Down
            ElseIf swings.Count > 0 AndAlso CurrentBar.High >= cs.EndPrice AndAlso cs.Direction = Direction.Up Then
                ' extension up
                cs.EndBar = CurrentBar.Number
                cs.EndPrice = CurrentBar.High
                If ChannelMode <> ChannelModeType.SetToBase Then
                    currentSwingLengthText.Location = New Point(cs.EndBar, cs.EndPrice)
                    currentSwingLengthText.Text = GetDollarValue(Abs(swings(swings.Count - 1).StartPrice - swings(swings.Count - 1).EndPrice)) & " "
                End If
                curSwingEvent = AutoTrend_old.SwingEvent.Extension
                swingDir = Direction.Up
            ElseIf swings.Count > 0 AndAlso CurrentBar.Low <= cs.EndPrice AndAlso cs.Direction = Direction.Down Then
                ' extension down
                cs.EndBar = CurrentBar.Number
                cs.EndPrice = CurrentBar.Low
                If ChannelMode <> ChannelModeType.SetToBase Then
                    currentSwingLengthText.Location = New Point(cs.EndBar, cs.EndPrice)
                    currentSwingLengthText.Text = GetDollarValue(Abs(swings(swings.Count - 1).StartPrice - swings(swings.Count - 1).EndPrice)) & " "
                End If
                curSwingEvent = AutoTrend_old.SwingEvent.Extension
                swingDir = Direction.Down
            End If
            If ChannelMode = ChannelModeType.SetToBase Then
                Dim scs As Swing = secondarySwings(secondarySwings.Count - 1)
                Dim srv As Decimal = RawRV
                If CurrentBar.High - scs.EndPrice >= srv AndAlso CurrentBar.Number <> scs.EndBar AndAlso scs.Direction = Direction.Down Then
                    'new swing up
                    If HideLastSwingLine AndAlso secondarySwings.Count > 0 And SwingLinesVisible Then AddObjectToChart(secondarySwings(secondarySwings.Count - 1).TL)
                    secondarySwings.Add(NewSwing(NeutralSwingLineColor, New Point(scs.EndBar, scs.EndPrice), New Point(CurrentBar.Number, CurrentBar.High), Not HideLastSwingLine And SwingLinesVisible, Direction.Up))
                    secondarySwings(secondarySwings.Count - 1).TL.Pen.Thickness = 2.6
                    currentSwingLengthText = NewLabel(GetDollarValue(Abs(secondarySwings(secondarySwings.Count - 1).StartPrice - secondarySwings(secondarySwings.Count - 1).EndPrice)) & " ", SwingLengthTextColor, New Point(secondarySwings(secondarySwings.Count - 1).EndBar, secondarySwings(secondarySwings.Count - 1).EndPrice), False)
                    currentSwingLengthText.HorizontalAlignment = LabelHorizontalAlignment.Right
                    currentSwingLengthText.VerticalAlignment = LabelVerticalAlignment.Top
                    If SwingLengthTextsVisible Then AddObjectToChart(currentSwingLengthText)
                ElseIf scs.EndPrice - CurrentBar.Low >= srv AndAlso CurrentBar.Number <> scs.EndBar AndAlso scs.Direction = Direction.Up Then
                    ' new swing down
                    If HideLastSwingLine AndAlso secondarySwings.Count > 0 And SwingLinesVisible Then AddObjectToChart(secondarySwings(secondarySwings.Count - 1).TL)
                    secondarySwings.Add(NewSwing(NeutralSwingLineColor, New Point(scs.EndBar, scs.EndPrice), New Point(CurrentBar.Number, CurrentBar.Low), Not HideLastSwingLine And SwingLinesVisible, Direction.Down))
                    secondarySwings(secondarySwings.Count - 1).TL.Pen.Thickness = 2.6
                    currentSwingLengthText = NewLabel(GetDollarValue(Abs(secondarySwings(secondarySwings.Count - 1).StartPrice - secondarySwings(secondarySwings.Count - 1).EndPrice)) & " ", SwingLengthTextColor, New Point(secondarySwings(secondarySwings.Count - 1).EndBar, secondarySwings(secondarySwings.Count - 1).EndPrice), False)
                    currentSwingLengthText.HorizontalAlignment = LabelHorizontalAlignment.Right
                    currentSwingLengthText.VerticalAlignment = LabelVerticalAlignment.Bottom
                    If SwingLengthTextsVisible Then AddObjectToChart(currentSwingLengthText)
                ElseIf secondarySwings.Count > 0 AndAlso CurrentBar.High >= scs.EndPrice AndAlso scs.Direction = Direction.Up Then
                    ' extension up
                    scs.EndBar = CurrentBar.Number
                    scs.EndPrice = CurrentBar.High
                    currentSwingLengthText.Location = New Point(scs.EndBar, scs.EndPrice)
                    currentSwingLengthText.Text = GetDollarValue(Abs(secondarySwings(secondarySwings.Count - 1).StartPrice - secondarySwings(secondarySwings.Count - 1).EndPrice)) & " "
                ElseIf secondarySwings.Count > 0 AndAlso CurrentBar.Low <= scs.EndPrice AndAlso scs.Direction = Direction.Down Then
                    ' extension down
                    scs.EndBar = CurrentBar.Number
                    scs.EndPrice = CurrentBar.Low
                    currentSwingLengthText.Location = New Point(scs.EndBar, scs.EndPrice)
                    currentSwingLengthText.Text = GetDollarValue(Abs(secondarySwings(secondarySwings.Count - 1).StartPrice - secondarySwings(secondarySwings.Count - 1).EndPrice)) & " "
                End If
            End If

            If curSwingEvent = SwingEvent.NewSwing Then
                'currentSwingCountGraphLine = NewTrendLine(If(swingDir = Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor), New Point(CurrentBar.Number, swingCountGraphYPlacement), New Point(CurrentBar.Number, swingCountGraphYPlacement))
                'currentSwingCountGraphLine.Pen.Thickness = 10
            End If




            ColorCurrentBars()

            DrawProjectionLineAndRVText()
            'check for removing of potential channels that are more than 3 swings in length
            If ChannelMode = ChannelModeType.Unmerged Then
                Dim i As Integer
                While i < channels.Count
                    Dim channel As Channel = channels(i)
                    If channel.IsConfirmed = False And channel.IsCut = False And channel.IsCancelled = False Then
                        If curSwingEvent = SwingEvent.NewSwing And channel.Direction <> swingDir Then
                            RemoveObjectFromChart(channel.TL)
                            channels.RemoveAt(i)
                            i -= 1
                        End If
                    End If
                    i += 1
                End While
            End If
            If swings.Count > 2 AndAlso curSwingEvent <> AutoTrend_old.SwingEvent.None Then ' AndAlso (channelLines.Count = 0 OrElse swingDir <> CurrentChannelLine.Direction) Then
                Dim aPoint As Point, bPoint As Point, cPoint As Point = New Point(CurrentSwing.EndBar, CurrentSwing.EndPrice)
                Dim setPoints As Boolean
                If ChannelMode = ChannelModeType.Merged Or ChannelMode = ChannelModeType.SetToBase Then
                    ' draw potential channel
                    Dim rangeBar As Integer
                    Dim rangePoint As Decimal = If(swingDir = Direction.Down, Decimal.MinValue, Decimal.MaxValue)
                    ' find B-point
                    For i = swings.Count - 1 To 0 Step -1
                        If (swingDir = Direction.Down And swings(i).StartPrice > rangePoint) Or
                            (swingDir = Direction.Up And swings(i).StartPrice < rangePoint) Then
                            rangeBar = swings(i).StartBar
                            rangePoint = swings(i).StartPrice
                        End If
                        If (swingDir = Direction.Down And swings(i).StartPrice < CurrentSwing.EndPrice) Or
                            (swingDir = Direction.Up And swings(i).StartPrice > CurrentSwing.EndPrice) Then Exit For
                    Next
                    bPoint = New Point(rangeBar, rangePoint)
                    ' find A-point 
                    Dim heightToMatch As Decimal = Round(If(swingDir = Direction.Down, bPoint.Y - CurrentSwing.EndPrice, CurrentSwing.EndPrice - bPoint.Y), 5)
                    Dim highPoint As Decimal, highBar As Integer, lowPoint As Decimal, lowBar As Integer
                    highPoint = Decimal.MinValue
                    lowPoint = Decimal.MaxValue
                    If swingDir = Direction.Down Then
                        For i = swings.Count - 2 To 0 Step -1
                            If swings(i).StartPrice < lowPoint Then
                                lowBar = swings(i).StartBar
                                lowPoint = swings(i).StartPrice
                                highPoint = Decimal.MinValue
                            Else
                                highPoint = Max(highPoint, swings(i).StartPrice)
                            End If
                            If highPoint <> Decimal.MinValue AndAlso highPoint - lowPoint > heightToMatch Or i = 0 Then
                                aPoint = New Point(lowBar, lowPoint)
                                Exit For
                            End If
                        Next
                    Else
                        For i = swings.Count - 2 To 0 Step -1
                            If swings(i).StartPrice > highPoint Then
                                highBar = swings(i).StartBar
                                highPoint = swings(i).StartPrice
                                lowPoint = Decimal.MaxValue
                            Else
                                lowPoint = Min(lowPoint, swings(i).StartPrice)
                            End If
                            If highPoint - lowPoint > heightToMatch Or i = 0 Then
                                aPoint = New Point(highBar, highPoint)
                                Exit For
                            End If
                        Next
                    End If
                    setPoints = True
                Else
                    If swingDir = Direction.Down Then
                        If CurrentSwing.EndPrice > CurrentSwing(1).StartPrice Then
                            aPoint = New Point(CurrentSwing(1).StartBar, CurrentSwing(1).StartPrice)
                            bPoint = New Point(CurrentSwing(1).EndBar, CurrentSwing(1).EndPrice)
                            cPoint = New Point(CurrentSwing.EndBar, CurrentSwing.EndPrice)
                            setPoints = True
                        End If
                    Else
                        If CurrentSwing.EndPrice < CurrentSwing(1).StartPrice Then
                            aPoint = New Point(CurrentSwing(1).StartBar, CurrentSwing(1).StartPrice)
                            bPoint = New Point(CurrentSwing(1).EndBar, CurrentSwing(1).EndPrice)
                            cPoint = New Point(CurrentSwing.EndBar, CurrentSwing.EndPrice)
                            setPoints = True
                        End If
                    End If
                End If
                ' draw potential channel if legal placement 
                Dim legal As Boolean
                If ChannelMode <> ChannelModeType.SetToBase Then legal = True
                If ChannelMode = ChannelModeType.SetToBase Then
                    If aPoint.X >= secondarySwings(secondarySwings.Count - 1).StartBar Then
                        legal = True
                    Else
                        legal = False
                    End If
                End If
                If ((swingDir = Direction.Down And aPoint.Y <= cPoint.Y) Or
                    (swingDir = Direction.Up And aPoint.Y >= cPoint.Y)) And setPoints And legal Then

                    If CurrentSwing.ChannelLine Is Nothing Then ' if no channel on current swing
                        Dim swingIndx As Integer
                        For j = swings.Count - 1 To 0 Step -1
                            If swings(j).StartBar = aPoint.X Then
                                swingIndx = j
                                Exit For
                            End If
                        Next
                        Dim channel As New Channel(NewTrendLine(If(swingDir = Direction.Down, PotentialUpChannelLineColor, PotentialDownChannelLineColor),
                                                              aPoint, CurrentSwing.TL.EndPoint, ChannelLinesVisible))
                        CurrentSwing.ChannelLine = channel
                        channel.Swing = CurrentSwing
                        channels.Add(channel)
                        ' properties
                        channel.TL.ExtendRight = True
                        channel.IsCancelled = False
                        channel.IsConfirmed = False
                        channel.IsCut = False
                        channel.Direction = Not swingDir
                        channel.TL.HasParallel = True
                        ' reset extension point
                        channel.DPoint = If(channel.Direction = Direction.Down, New Point(0, Double.MaxValue), New Point(0, Double.MinValue))

                        BackupChannel(channel)
                    Else
                        ' update points
                        If CurrentChannelLine IsNot Nothing Then
                            CurrentChannelLine.TL.EndPoint = CurrentSwing.TL.EndPoint
                            If setPoints Then CurrentChannelLine.TL.StartPoint = aPoint
                        End If
                    End If
                    ' update
                    If CurrentChannelLine IsNot Nothing Then
                        If setPoints Then
                            CurrentChannelLine.APoint = aPoint
                            CurrentChannelLine.BPoint = bPoint
                            CurrentChannelLine.CPoint = cPoint
                            CurrentChannelLine.TL.ParallelDistance = bPoint.Y - LinCalc(aPoint.X, aPoint.Y, cPoint.X, cPoint.Y, bPoint.X)
                        End If
                        CurrentSwing.ChannelLine = CurrentChannelLine
                        CurrentChannelLine.Swing = CurrentSwing
                    End If
                End If
                ' check current potential channel for cancelling
                If swings.Count > 0 AndAlso CurrentSwing.ChannelLine IsNot Nothing AndAlso CurrentSwing.ChannelLine.IsCancelled = False Then
                    If (CurrentSwing.ChannelLine.Direction = Direction.Down And CurrentSwing.EndPrice >= CurrentSwing.ChannelLine.APoint.Y) Or
                        (CurrentSwing.ChannelLine.Direction = Direction.Up And CurrentSwing.EndPrice <= CurrentSwing.ChannelLine.APoint.Y) Then ' if price crosses cancel point
                        ' cancel
                        CurrentSwing.ChannelLine.IsCancelled = True
                        channels.Remove(CurrentSwing.ChannelLine)
                        RemoveObjectFromChart(CurrentSwing.ChannelLine.TL)
                        ShowNextBackedUpChannel(CurrentSwing.ChannelLine.Direction, False)
                        CurrentSwing.ChannelLine = Nothing
                    End If
                End If

                ' check to remove current partially cut channel
                If HighlightLastCutChannel AndAlso currentPartiallyCutChannel IsNot Nothing AndAlso swings.Count - 1 > currentPartiallyCutChannel.SwingNum Then
                    Dim swingLowPoint As Decimal = Min(swings(currentPartiallyCutChannel.SwingNum).EndPrice, swings(currentPartiallyCutChannel.SwingNum).StartPrice)
                    Dim swingHighPoint As Decimal = Max(swings(currentPartiallyCutChannel.SwingNum).EndPrice, swings(currentPartiallyCutChannel.SwingNum).StartPrice)
                    If CurrentSwing.EndPrice <= swingLowPoint Or CurrentSwing.EndPrice >= swingHighPoint Then
                        FullyCutChannel(currentPartiallyCutChannel.Channel)
                        currentPartiallyCutChannel = Nothing
                    End If
                End If

                Dim indx As Integer
                While indx < channels.Count
                    Dim channel As Channel = channels(indx)
                    ' remove channels for crossing the left side of the chart
                    If channel.IsCancelled = False Then
                        If ShowOnlyChannelsOnScreen Then
                            If channel.TL.StartPoint.X < Chart.Bounds.X1 Then ' if channel startpoint is off the left of the chart
                                RemoveObjectFromChart(channel.TL)
                            ElseIf (
                                    (channel.IsCut = False And ChannelLinesVisible) Or
                                    (channel.IsCut And
                                        (
                                             (channel.IsConfirmed And ConfirmedHistoryChannelLinesVisible) Or
                                             (channel.IsConfirmed = False And PotentialHistoryChannelLinesVisible)
                                         )
                                    )
                                   ) And
                                    channel.IsBackedUp = False Then
                                AddObjectToChart(channel.TL)
                            End If
                        ElseIf ((channel.IsCut = False And ChannelLinesVisible) Or (channel.IsCut And ((channel.IsConfirmed And ConfirmedHistoryChannelLinesVisible) Or (channel.IsConfirmed = False And PotentialHistoryChannelLinesVisible)))) And channel.IsBackedUp = False Then
                            AddObjectToChart(channel.TL)
                        End If
                    End If
                    If channel.IsCut = False Then
                        ' check to update BCSwingMatched flag
                        If channel.IsConfirmed And channel.BCSwingMatched = False And swingDir <> channel.Direction And CurrentSwing.TL.EndPoint <> channel.Swing.TL.EndPoint Then
                            If Abs(bPoint.Y - cPoint.Y) >= Abs(channel.BPoint.Y - channel.CPoint.Y) Then ' if bc swing length matched
                                channel.BCSwingMatched = True
                            End If
                        End If
                        ' check potential channels for confirmation
                        If channel.IsConfirmed = False And channel.IsCancelled = False Then
                            If (channel.Direction = Direction.Down And CurrentSwing.EndPrice <= channel.BPoint.Y) Or
                                (channel.Direction = Direction.Up And CurrentSwing.EndPrice >= channel.BPoint.Y) Then
                                ' confirm channel
                                channel.IsConfirmed = True
                                channel.TL.Pen = New Pen(New SolidColorBrush(If(channel.Direction = Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor)), 1)
                                'NewLabel(channel.TL.EndPoint.ToString, Colors.White, channel.TL.EndPoint, True)

                                If ColorBars Then
                                    If ChannelMode = ChannelModeType.Merged Or ChannelMode = ChannelModeType.SetToBase Then
                                        BarColor(channel.APoint.X, CurrentBar.Number - 1, If(channel.Direction = Direction.Down, DownTrendBarColor, UpTrendBarColor), If(channel.Direction = Direction.Down, DownTrendSwingLineColor, UpTrendSwingLineColor))
                                    Else
                                        Dim r = GetLastSingleChannel()
                                        If r <> -2 Then
                                            If r = Direction.Up Then
                                                BarColor(Min(CurrentSwing(2).StartBar, Chart.bars.Count - 1), Min(CurrentSwing.EndBar, Chart.bars.Count - 1), UpTrendBarColor, UpTrendSwingLineColor)
                                            Else
                                                BarColor(Min(CurrentSwing(2).StartBar, Chart.bars.Count - 1), Min(CurrentSwing.EndBar, Chart.bars.Count - 1), DownTrendBarColor, DownTrendSwingLineColor)
                                            End If
                                        End If
                                    End If
                                End If

                                Dim bcLength As Decimal = Abs(channel.CPoint.Y - channel.BPoint.Y)
                                ' bc text
                                channel.BCLengthText = NewLabel(FormatNumber(GetDollarValue(bcLength), DecimalPlaces, TriState.True), If(channel.Direction = Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor), AddToX(channel.CPoint, -2), BCLengthTextsVisible And channel.IsBackedUp = False)
                                channel.BCLengthText.HorizontalAlignment = LabelHorizontalAlignment.Right
                                channel.BCLengthText.VerticalAlignment = LabelVerticalAlignment.Top
                                ' target text
                                channel.TargetText = NewLabel("- " & FormatNumber(GetDollarValue(bcLength), DecimalPlaces), If(channel.Direction = Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor), New Point(CurrentBar.Number, CurrentSwing.EndPrice - BooleanToInteger(channel.Direction) * bcLength), BCTargetTextsVisible)
                                channel.TargetText.VerticalAlignment = LabelVerticalAlignment.Center
                                channel.TargetText.HorizontalAlignment = LabelHorizontalAlignment.Left
                                ' extension point
                                channel.DPoint = CurrentSwing.TL.EndPoint
                                ' swing lines
                                'channel.ABSwingLine = NewTrendLine(If(channel.Direction = Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor), channel.APoint, channel.BPoint, ChannelLinesVisible)
                                'channel.ABSwingLine.Pen.Thickness = 2
                                channel.BCSwingLine = NewTrendLine(If(channel.Direction = Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor), channel.BPoint, channel.CPoint, False)
                                channel.BCSwingLine.Pen.Thickness = 2
                                'channel.CDSwingLine = NewTrendLine(If(channel.Direction = Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor), channel.CPoint, channel.DPoint, ChannelLinesVisible)
                                'channel.CDSwingLine.Pen.Thickness = 2

                                BackupChannel(channel)
                                ShowNextBackedUpChannel(channel.Direction, False)
                            End If
                        End If
                        ' update D-point (extend)
                        If channel.IsConfirmed And swingDir = channel.Direction Then
                            If (swingDir = Direction.Down And CurrentSwing.EndPrice <= channel.DPoint.Y) Or
                                (swingDir = Direction.Up And CurrentSwing.EndPrice >= channel.DPoint.Y) Then ' if extension
                                channel.DPoint = CurrentSwing.TL.EndPoint
                                If ChannelMode = ChannelModeType.Merged Or ChannelMode = ChannelModeType.SetToBase Then
                                    BarColor(channel.APoint.X, CurrentBar.Number - 1, If(channel.Direction = Direction.Down, DownTrendBarColor, UpTrendBarColor), If(channel.Direction = Direction.Down, DownTrendSwingLineColor, UpTrendSwingLineColor))
                                Else

                                End If
                                'channel.CDSwingLine.EndPoint = channel.DPoint
                            End If
                        End If
                        ' check channel for BC swing length match
                        If channel.IsConfirmed And channel.BCSwingLineRemoved = False And channel.BCSwingMatched And swingDir <> channel.Direction Then
                            channel.TL.Pen = New Pen(New SolidColorBrush(If(channel.Direction = Direction.Down, ConfirmedHistoryDownChannelLineColor, ConfirmedHistoryUpChannelLineColor)), 1)
                            'channel.ABSwingLine.Pen = New Pen(New SolidColorBrush(If(channel.Direction = Direction.Down, ConfirmedHistoryDownChannelLineColor, ConfirmedHistoryUpChannelLineColor)), 1)
                            channel.BCSwingLine.Pen = New Pen(New SolidColorBrush(If(channel.Direction = Direction.Down, ConfirmedHistoryDownChannelLineColor, ConfirmedHistoryUpChannelLineColor)), 1)
                            'channel.CDSwingLine.Pen = New Pen(New SolidColorBrush(If(channel.Direction = Direction.Down, ConfirmedHistoryDownChannelLineColor, ConfirmedHistoryUpChannelLineColor)), 1)
                            'RemoveObjectFromChart(channel.ABSwingLine)
                            'RemoveObjectFromChart(channel.BCSwingLine)
                            'RemoveObjectFromChart(channel.CDSwingLine)
                            RemoveObjectFromChart(channel.BCLengthText)
                            RemoveObjectFromChart(channel.TargetText)
                            channel.BCSwingLineRemoved = True
                            ShowNextBackedUpChannel(channel.Direction, True)
                        End If
                        ' check channels for hit
                        If channel.IsCancelled = False And channel.CutBarNumber = -1 And swingDir <> channel.Direction And channel.CPoint <> CurrentSwing.TL.EndPoint Then
                            If (channel.Direction = Direction.Down AndAlso CurrentBar.High > LinCalc(channel.TL.StartPoint.X, channel.TL.StartPoint.Y, channel.TL.EndPoint.X, channel.TL.EndPoint.Y, CurrentBar.Number)) OrElse
                                (channel.Direction = Direction.Up AndAlso CurrentBar.Low < LinCalc(channel.TL.StartPoint.X, channel.TL.StartPoint.Y, channel.TL.EndPoint.X, channel.TL.EndPoint.Y, CurrentBar.Number)) Then ' if base line has been crossed
                                channel.CutBarNumber = CurrentBar.Number
                            End If
                        End If
                        ' check channels to cut
                        If channel.CutBarNumber <> -1 And channel.CPoint <> CurrentSwing.TL.EndPoint And swingDir <> channel.Direction And
                            (
                                (channel.IsConfirmed And channel.BCSwingMatched) Or
                                (
                                    channel.IsConfirmed = False And channel.IsCancelled = False And
                                    (
                                        (channel.Direction = Direction.Down And CurrentSwing.EndPrice >= channel.CPoint.Y) Or
                                        (channel.Direction = Direction.Up And CurrentSwing.EndPrice <= channel.CPoint.Y)
                                    )
                                )
                            ) Then
                            CutChannel(channel)
                        End If
                        If channel.IsConfirmed And channel.BCSwingMatched And swingDir = channel.Direction And channel.IsGapped = False Then
                            ' gap channel
                            channel.IsGapped = True
                            channel.IsBackedUp = False
                            channel.TL.Pen = New Pen(New SolidColorBrush(If(channel.Direction = Direction.Down, GappedDownChannelLineColor, GappedUpChannelLineColor)), 1)
                            RemoveObjectFromChart(channel.BCLengthText)
                            'RemoveObjectFromChart(channel.ABSwingLine)
                            'RemoveObjectFromChart(channel.BCSwingLine)
                            'RemoveObjectFromChart(channel.CDSwingLine)
                            ShowNextBackedUpChannel(channel.Direction, True)
                        End If
                    End If
                    indx += 1
                End While
            End If
            If curSwingEvent = SwingEvent.NewSwing Then RemoveSwingChannel()
            If swings.Count > 0 And CurrentSwingChannelLineVisible Then ProcessSwingChannel(CurrentSwing)
            ProcessCurrentGapMark()
            ' check to remove partially cut channel
            If HighlightLastCutChannel AndAlso currentPartiallyCutChannel IsNot Nothing Then
                For Each channel In channels
                    If channel.IsConfirmed And channel.IsGapped = False And channel.APoint.X > currentPartiallyCutChannel.Channel.CPoint.X Then
                        FullyCutChannel(currentPartiallyCutChannel.Channel)
                        currentPartiallyCutChannel = Nothing
                        Exit For
                    End If
                Next
            End If
        End Sub

        Private Sub ColorCurrentBars()
            If ColorBars Then
                barColorsDirty = True
                CType(Chart.bars(CurrentBar.Number - 1).Pen.Brush, SolidColorBrush).Color = NeutralBarColor
                RefreshObject(Chart.bars(CurrentBar.Number - 1))
                If curSwingEvent = SwingEvent.Extension Or curSwingEvent = SwingEvent.NewSwing Then
                    If ChannelMode = ChannelModeType.Merged Or ChannelMode = ChannelModeType.SetToBase Then
                        Dim curChannel As Channel = Nothing
                        For i = channels.Count - 1 To 0 Step -1
                            If channels(i).IsConfirmed Then
                                Dim count As Integer
                                For Each swing In swings
                                    If swing.StartBar >= channels(i).APoint.X And swing.EndBar <= channels(i).CPoint.X Then
                                        count += 1
                                    End If
                                Next
                                If count = 3 Then
                                    curChannel = channels(i)
                                    Exit For
                                End If
                            End If
                        Next
                        If curChannel IsNot Nothing AndAlso curChannel.Direction = CurrentSwing.Direction Then
                            If (curChannel.Direction = Direction.Down And CurrentSwing.EndPrice <= curChannel.DPoint.Y) Or
                                (curChannel.Direction = Direction.Up And CurrentSwing.EndPrice >= curChannel.DPoint.Y) Then
                                BarColor(curChannel.APoint.X, CurrentBar.Number - 1, If(curChannel.Direction = Direction.Down, DownTrendBarColor, UpTrendBarColor), If(curChannel.Direction = Direction.Down, DownTrendSwingLineColor, UpTrendSwingLineColor))
                            End If
                        End If
                    Else
                        Dim r = GetLastSingleChannel()
                        If r <> -2 Then
                            If r = Direction.Up Then
                                BarColor(Min(CurrentSwing.StartBar, Chart.bars.Count), Min(CurrentSwing.EndBar, Chart.bars.Count - 1), UpTrendBarColor, UpTrendSwingLineColor)
                            Else
                                BarColor(Min(CurrentSwing.StartBar, Chart.bars.Count), Min(CurrentSwing.EndBar, Chart.bars.Count - 1), DownTrendBarColor, DownTrendSwingLineColor)
                            End If
                        End If
                    End If
                End If
            End If
        End Sub
        Private Function GetLastSingleChannel() As Integer
            If swings.Count > 2 Then
                If CurrentSwing(2).StartPrice > CurrentSwing(2).EndPrice And
                    CurrentSwing(1).EndPrice < CurrentSwing(2).StartPrice And
                    CurrentSwing(0).EndPrice <= CurrentSwing(1).StartPrice Then
                    Return Direction.Down
                ElseIf CurrentSwing(2).StartPrice < CurrentSwing(2).EndPrice And
                    CurrentSwing(1).EndPrice > CurrentSwing(2).StartPrice And
                    CurrentSwing(0).EndPrice >= CurrentSwing(1).StartPrice Then
                    Return Direction.Up
                End If
            End If
            Return -2
        End Function
        'Protected Sub BarColor(channel As Channel, startBar As Integer, endBar As Integer, ByVal color As Color, ByVal swingColor As Color)
        '    If ColorBars Then
        '        If colorMergedChannels Then
        '            Dim swingsToColor As New List(Of Swing)
        '            For Each swing In swings
        '                If swing.StartBar >= startBar And swing.EndBar <= endBar + 1 Then
        '                    swingsToColor.Add(swing)
        '                End If
        '            Next
        '            Dim pointToStartColoringBars As Integer = 0
        '            For Each stepChannel In channels
        '                If stepChannel.APoint.X > startBar And stepChannel.CPoint.X < endBar And stepChannel.IsConfirmed And stepChannel.Direction <> channel.Direction Then
        '                    pointToStartColoringBars = Max(pointToStartColoringBars, stepChannel.CPoint.X)
        '                End If
        '            Next
        '            If pointToStartColoringBars <> 0 Then
        '                Dim i As Integer
        '                Do While i < swingsToColor.Count
        '                    If swingsToColor(i).StartBar < pointToStartColoringBars Then swingsToColor.RemoveAt(i) Else Exit Do
        '                Loop
        '                If swingsToColor.Count < 3 Then
        '                    swingsToColor.Clear()
        '                Else
        '                    Dim met As Boolean
        '                    For Each channel In channels
        '                        If channel.IsCancelled = False And channel.APoint.X = swingsToColor(0).StartBar Then met = True
        '                    Next
        '                    If Not met Then swingsToColor.Clear()
        '                End If
        '            End If
        '            For Each swing In swingsToColor
        '                If CType(swing.TL.Pen.Brush, SolidColorBrush).Color = swingColor Or CType(swing.TL.Pen.Brush, SolidColorBrush).Color = NeutralSwingLineColor Then
        '                    swing.TL.Pen.Brush = New SolidColorBrush(swingColor)
        '                    For i = swing.StartBar To Min(swing.EndBar, Chart.bars.Count - 1)
        '                        If CType(Chart.bars(i).Pen.Brush, SolidColorBrush).Color <> color Then
        '                            Chart.bars(i).Pen.Brush = New SolidColorBrush(color)
        '                            RefreshObject(Chart.bars(i))
        '                        End If
        '                    Next
        '                End If
        '            Next
        '        Else
        '            For Each swing In swings
        '                If swing.StartBar >= startBar And swing.EndBar <= endBar + 1 Then
        '                    swing.TL.Pen.Brush = New SolidColorBrush(swingColor)
        '                End If
        '            Next
        '            For i = startBar To endBar
        '                If CType(Chart.bars(i).Pen.Brush, SolidColorBrush).Color <> color Then
        '                    Chart.bars(i).Pen.Brush = New SolidColorBrush(color)
        '                    RefreshObject(Chart.bars(i))
        '                End If
        '            Next
        '        End If
        '    End If
        'End Sub
        Protected Sub BarColor(ByVal startBar As Integer, ByVal endBar As Integer, ByVal color As Color, ByVal swingColor As Color)
            Dim swingsToColor As New List(Of Swing)
            If ChannelMode = ChannelModeType.SetToBase Then
                For Each swing In secondarySwings
                    If swing.StartBar >= startBar And swing.EndBar <= endBar + 1 Then
                        swing.TL.Pen.Brush = New SolidColorBrush(swingColor)
                    End If
                Next
            End If
            For Each swing In swings
                If swing.StartBar >= startBar And swing.EndBar <= endBar + 1 Then
                    swing.TL.Pen.Brush = New SolidColorBrush(swingColor)
                End If
            Next
            For i = startBar To endBar
                If CType(Chart.bars(i).Pen.Brush, SolidColorBrush).Color <> color Then
                    Chart.bars(i).Pen.Brush = New SolidColorBrush(color)
                    RefreshObject(Chart.bars(i))
                End If
            Next
        End Sub
        Private Sub DrawProjectionLineAndRVText()
            ' draw projection line
            Dim cs = CurrentSwing
            Dim rv = Me.RV
            Dim averageSwingAngle As Double = GetAverageSwingAngle()
            If averageSwingAngle <> 0 Then
                rvProNewLine.StartPoint = New Point(cs.EndBar, cs.EndPrice)
                rvProExtLine.StartPoint = New Point(cs.StartBar, cs.StartPrice)
                Dim newLineBarSkip As Integer
                Dim extLineBarSkip As Integer
                If Chart.Settings("IsSlaveChart").Value Then
                    newLineBarSkip = 1
                    extLineBarSkip = 1
                Else
                    newLineBarSkip = Abs(CurrentBar.Close - (cs.EndPrice - BooleanToInteger(cs.Direction) * rv)) / Chart.Settings("RangeValue").Value * 2
                    extLineBarSkip = Abs(CurrentBar.Close - cs.EndPrice) / Chart.Settings("RangeValue").Value * 2
                End If
                Dim endBar As Integer = Max(cs.EndBar + Round(rv / Tan(averageSwingAngle), 0), CurrentBar.Number + newLineBarSkip)
                rvProNewLine.EndPoint = New Point(endBar, cs.EndPrice - BooleanToInteger(cs.Direction) * rv)
                rvProExtLine.EndPoint = New Point(CurrentBar.Number + extLineBarSkip, cs.EndPrice)
                rvText.Location = New Point(endBar, cs.EndPrice - BooleanToInteger(cs.Direction) * rv)
                averageSwingAngle = Atan(Abs(rvProNewLine.EndPoint.Y - rvProNewLine.StartPoint.Y) / Abs(rvProNewLine.EndPoint.X - rvProNewLine.StartPoint.X))
                If ChannelMode <> ChannelModeType.SetToBase Then
                    ' move target texts along
                    For Each channel In channels
                        If channel.TargetText IsNot Nothing Then
                            Dim bcHeight As Decimal = Abs(channel.BPoint.Y - channel.CPoint.Y)
                            Dim yPoint As Double = channel.DPoint.Y - BooleanToInteger(channel.Direction) * bcHeight
                            If Chart.Settings("IsSlaveChart").Value Then
                                newLineBarSkip = 1
                            Else
                                newLineBarSkip = Abs(CurrentBar.Close - yPoint) / Chart.Settings("RangeValue").Value * 2
                            End If
                            endBar = Max(cs.EndBar + Round(bcHeight / Tan(averageSwingAngle), 0), CurrentBar.Number + newLineBarSkip)
                            channel.TargetText.Location = New Point(endBar, yPoint)
                        End If
                    Next
                End If
            Else
                rvText.Location = New Point(CurrentBar.Number, cs.EndPrice - BooleanToInteger(cs.Direction) * rv)
                If ChannelMode <> ChannelModeType.SetToBase Then
                    ' move target texts along
                    For Each channel In channels
                        If channel.TargetText IsNot Nothing Then
                            channel.TargetText.Location = New Point(CurrentBar.Number + 1, channel.DPoint.Y + BooleanToInteger(channel.Direction) * (channel.BPoint.Y - channel.CPoint.Y))
                        End If
                    Next
                End If
            End If
            rvText.Text = "- " & FormatNumber(GetDollarValue(rv), DecimalPlaces)
            DrawProjectionSecondaryRVText()
        End Sub
        Private Sub DrawProjectionSecondaryRVText()
            If ChannelMode = ChannelModeType.SetToBase Then
                Dim cs As Swing = secondarySwings(secondarySwings.Count - 1)
                Dim rv As Decimal = Me.RawRV
                Dim averageSwingAngle As Double = GetAverageSwingAngle()
                If averageSwingAngle <> 0 Then
                    rvProNewLine.StartPoint = New Point(cs.EndBar, cs.EndPrice)
                    rvProExtLine.StartPoint = New Point(cs.StartBar, cs.StartPrice)
                    Dim newLineBarSkip As Integer
                    Dim extLineBarSkip As Integer
                    If Chart.Settings("IsSlaveChart").Value Then
                        newLineBarSkip = 1
                        extLineBarSkip = 1
                    Else
                        newLineBarSkip = Abs(CurrentBar.Close - (cs.EndPrice - BooleanToInteger(cs.Direction) * rv)) / Chart.Settings("RangeValue").Value * 2
                        extLineBarSkip = Abs(CurrentBar.Close - cs.EndPrice) / Chart.Settings("RangeValue").Value * 2
                    End If
                    Dim endBar As Integer = Max(cs.EndBar + Round(rv / Tan(averageSwingAngle), 0), CurrentBar.Number + newLineBarSkip)
                    rvProNewLine.EndPoint = New Point(endBar, cs.EndPrice - BooleanToInteger(cs.Direction) * rv)
                    rvProExtLine.EndPoint = New Point(CurrentBar.Number + extLineBarSkip, cs.EndPrice)

                    rvSecondaryText.Location = New Point(endBar, cs.EndPrice - BooleanToInteger(cs.Direction) * rv)
                    averageSwingAngle = Atan(Abs(rvProNewLine.EndPoint.Y - rvProNewLine.StartPoint.Y) / Abs(rvProNewLine.EndPoint.X - rvProNewLine.StartPoint.X))
                    ' move target texts along
                    For Each channel In channels
                        If channel.TargetText IsNot Nothing Then
                            Dim bcHeight As Decimal = Abs(channel.BPoint.Y - channel.CPoint.Y)
                            Dim yPoint As Double = channel.DPoint.Y - BooleanToInteger(channel.Direction) * bcHeight
                            If Chart.Settings("IsSlaveChart").Value Then
                                newLineBarSkip = 1
                            Else
                                newLineBarSkip = Abs(CurrentBar.Close - yPoint) / Chart.Settings("RangeValue").Value * 2
                            End If
                            endBar = Max(cs.EndBar + Round(bcHeight / Tan(averageSwingAngle), 0), CurrentBar.Number + newLineBarSkip)
                            channel.TargetText.Location = New Point(endBar, yPoint)
                        End If
                    Next
                Else
                    rvSecondaryText.Location = New Point(CurrentBar.Number, cs.EndPrice - BooleanToInteger(cs.Direction) * rv)
                    ' move target texts along
                    For Each channel In channels
                        If channel.TargetText IsNot Nothing Then
                            channel.TargetText.Location = New Point(CurrentBar.Number + 1, channel.DPoint.Y + BooleanToInteger(channel.Direction) * (channel.BPoint.Y - channel.CPoint.Y))
                        End If
                    Next
                End If
                rvSecondaryText.Text = "- " & FormatNumber(GetDollarValue(rv), DecimalPlaces)
            End If
        End Sub
        Private Sub ProcessCurrentGapMark()
            If curSwingEvent = AutoTrend_old.SwingEvent.NewSwing Then
                If swings.Count > 1 AndAlso currentGapMark.Swing Is CurrentSwing(1) Then currentGapMark.State = GapMarkerState.FollowsExtension
                If swings.Count > 2 AndAlso currentGapMark.Swing Is CurrentSwing(2) Then currentGapMark.State = GapMarkerState.Inactive
            End If
            If swings.Count > 2 Then
                Dim p As Double = CurrentBar.Close
                If (CurrentSwing.Direction = Direction.Down And p < CurrentSwing(2).EndPrice - RV) Or
                    (CurrentSwing.Direction = Direction.Up And p > CurrentSwing(2).EndPrice + RV) Then ' if gap is being created
                    If currentGapMark.Swing IsNot CurrentSwing Then ' if new gap
                        'If currentGapMark.Line IsNot Nothing Then AddObjectToChart(currentGapMark.Line)
                        currentGapMark.Swing = CurrentSwing
                        currentGapMark.Line = NewTrendLine(If(CurrentSwing.Direction = Direction.Down, DownGapMarkerColor, UpGapMarkerColor), New Point(0, 0), New Point(0, 0), True)
                        currentGapMark.Line.Pen.Thickness = 7
                        currentGapMark.State = GapMarkerState.FollowsRVPoint
                    End If
                    currentGapMark.Line.StartPoint = New Point(LinCalc(CurrentSwing.StartPrice, CurrentSwing.StartBar, CurrentSwing.EndPrice, CurrentSwing.EndBar, CurrentSwing(2).EndPrice), CurrentSwing(2).EndPrice)
                End If
                If currentGapMark.Swing Is CurrentSwing(1) Then
                    If (currentGapMark.Swing.Direction = Direction.Up And p <= currentGapMark.Line.StartPoint.Y) Or
                        (currentGapMark.Swing.Direction = Direction.Down And p >= currentGapMark.Line.StartPoint.Y) Then
                        currentGapMark.Swing = Nothing
                        RemoveObjectFromChart(currentGapMark.Line)
                        currentGapMark.Line = Nothing
                        currentGapMark.State = GapMarkerState.Inactive
                    End If
                End If
                If currentGapMark.State = GapMarkerState.FollowsRVPoint Then
                    currentGapMark.Line.EndPoint = New Point(LinCalc(currentGapMark.Swing.StartPrice, currentGapMark.Swing.StartBar, currentGapMark.Swing.EndPrice, currentGapMark.Swing.EndBar,
                                                                     currentGapMark.Swing.EndPrice - BooleanToInteger(currentGapMark.Swing.Direction) * RV), currentGapMark.Swing.EndPrice - BooleanToInteger(currentGapMark.Swing.Direction) * RV)
                ElseIf currentGapMark.State = GapMarkerState.FollowsExtension Then
                    currentGapMark.Line.EndPoint = New Point(LinCalc(currentGapMark.Swing.StartPrice, currentGapMark.Swing.StartBar, currentGapMark.Swing.EndPrice, currentGapMark.Swing.EndBar, CurrentSwing.EndPrice), CurrentSwing.EndPrice)
                End If
            End If
        End Sub
        Protected Sub ProcessSwingChannel(ByVal swing As Swing)
            If Chart.bars.Count <= 1 Then Exit Sub
            If swing.Direction = Direction.Down And swings.Count > 0 Then
                If Not swingChannel.IsActive Then
                    Dim highBar As New Point
                    Dim lowBar As New Point(0, Double.MaxValue)
                    Dim bPoint As Point, cPoint As Point, rvMatched As Boolean
                    Dim prevHighest As Double
                    For i = swing.StartBar - 1 To CurrentBar.Number - 1
                        If Bars(i).Low < lowBar.Y Then
                            lowBar = New Point(i + 1, Bars(i).Low)
                            highBar = New Point(0, 0)
                        End If
                        If Bars(i).High >= highBar.Y Then highBar = New Point(i + 1, Bars(i).High)
                        If highBar.Y - lowBar.Y >= SwingRV And highBar.Y - lowBar.Y >= prevHighest Then
                            bPoint = lowBar
                            cPoint = highBar
                            prevHighest = highBar.Y - lowBar.Y
                            rvMatched = True
                        End If
                    Next
                    If rvMatched Then
                        With swingChannel
                            .IsActive = True
                            .APoint = swing.TL.StartPoint
                            .BPoint = bPoint
                            .CPoint = cPoint
                            .TL = NewTrendLine(NeutralSwingLineColor, swing.TL.StartPoint, cPoint)
                            .TL.HasParallel = True
                            .TL.ParallelDistance = .BPoint.Y - LinCalc(.APoint.X, .APoint.Y, .CPoint.X, .CPoint.Y, .BPoint.X)
                            .TL.ExtendRight = True
                        End With
                    End If
                End If
                If swingChannel.IsActive And Not swingChannel.IsConfirmed Then
                    Dim lowBar As New Point(0, Double.MaxValue)
                    Dim highBar As New Point
                    For i = swingChannel.CPoint.X - 1 To CurrentBar.Number - 1
                        If Bars(i).Low <= lowBar.Y Then lowBar = New Point(i + 1, Bars(i).Low)
                        If Bars(i).High >= highBar.Y Then highBar = New Point(i + 1, Bars(i).High)
                    Next
                    If highBar.Y >= swingChannel.CPoint.Y Then
                        With swingChannel
                            .CPoint = highBar
                            .TL.EndPoint = highBar
                            .TL.ParallelDistance = .BPoint.Y - LinCalc(.APoint.X, .APoint.Y, .CPoint.X, .CPoint.Y, .BPoint.X)
                        End With
                    End If
                    If lowBar.Y < swingChannel.BPoint.Y Then
                        swingChannel.IsConfirmed = True
                        swingChannel.BCSwingLine = NewTrendLine(NeutralSwingLineColor, swingChannel.BPoint, swingChannel.CPoint, False)
                    End If
                End If
                If swingChannel.IsConfirmed Then
                    Dim highBar As Point
                    For i = swing.EndBar - 1 To CurrentBar.Number - 1
                        If Bars(i).High > highBar.Y Then highBar = New Point(i + 1, Bars(i).High)
                    Next
                    If highBar.Y - swing.EndPrice >= Abs(swingChannel.BCSwingLine.EndPoint.Y - swingChannel.BCSwingLine.StartPoint.Y) Then
                        With swingChannel
                            .IsConfirmed = False
                            .CPoint = highBar
                            .BPoint = New Point(swing.EndBar, swing.EndPrice)
                            .TL.EndPoint = highBar
                            .TL.ParallelDistance = .BPoint.Y - LinCalc(.APoint.X, .APoint.Y, .CPoint.X, .CPoint.Y, .BPoint.X)
                            'RemoveObjectFromChart(.BCSwingLine)
                        End With
                    End If
                End If
            Else
                ' up
                If Not swingChannel.IsActive Then
                    Dim highBar As New Point
                    Dim lowBar As New Point(0, Double.MaxValue)
                    Dim bPoint As Point, cPoint As Point, rvMatched As Boolean
                    Dim prevHighest As Double
                    For i = swing.StartBar - 1 To CurrentBar.Number - 1
                        If Bars(i).High > highBar.Y Then
                            highBar = New Point(i + 1, Bars(i).High)
                            lowBar = New Point(0, Double.MaxValue)
                        End If
                        If Bars(i).Low <= lowBar.Y Then lowBar = New Point(i + 1, Bars(i).Low)
                        If highBar.Y - lowBar.Y >= SwingRV And highBar.Y - lowBar.Y >= prevHighest Then
                            bPoint = highBar
                            cPoint = lowBar
                            prevHighest = highBar.Y - lowBar.Y
                            rvMatched = True
                        End If
                    Next
                    If rvMatched Then
                        With swingChannel
                            .IsActive = True
                            .APoint = swing.TL.StartPoint
                            .BPoint = bPoint
                            .CPoint = cPoint
                            .TL = NewTrendLine(NeutralSwingLineColor, swing.TL.StartPoint, cPoint)
                            .TL.HasParallel = True
                            .TL.ParallelDistance = .BPoint.Y - LinCalc(.APoint.X, .APoint.Y, .CPoint.X, .CPoint.Y, .BPoint.X)
                            .TL.ExtendRight = True
                        End With
                    End If
                End If
                If swingChannel.IsActive And Not swingChannel.IsConfirmed Then
                    Dim lowBar As New Point(0, Double.MaxValue)
                    Dim highBar As New Point
                    For i = swingChannel.CPoint.X - 1 To CurrentBar.Number - 1
                        If Bars(i).Low <= lowBar.Y Then lowBar = New Point(i + 1, Bars(i).Low)
                        If Bars(i).High >= highBar.Y Then highBar = New Point(i + 1, Bars(i).High)
                    Next
                    If lowBar.Y <= swingChannel.CPoint.Y Then
                        With swingChannel
                            .CPoint = lowBar
                            .TL.EndPoint = lowBar
                            .TL.ParallelDistance = .BPoint.Y - LinCalc(.APoint.X, .APoint.Y, .CPoint.X, .CPoint.Y, .BPoint.X)
                        End With
                    End If
                    If highBar.Y > swingChannel.BPoint.Y Then
                        swingChannel.IsConfirmed = True
                        swingChannel.BCSwingLine = NewTrendLine(NeutralSwingLineColor, swingChannel.BPoint, swingChannel.CPoint, False)
                    End If
                End If
                If swingChannel.IsConfirmed Then
                    Dim lowBar As New Point(0, Double.MaxValue)
                    For i = swing.EndBar - 1 To CurrentBar.Number - 1
                        If Bars(i).Low < lowBar.Y Then lowBar = New Point(i + 1, Bars(i).Low)
                    Next
                    If swing.EndPrice - lowBar.Y >= Abs(swingChannel.BCSwingLine.EndPoint.Y - swingChannel.BCSwingLine.StartPoint.Y) Then
                        With swingChannel
                            .IsConfirmed = False
                            .CPoint = lowBar
                            .BPoint = New Point(swing.EndBar, swing.EndPrice)
                            .TL.EndPoint = lowBar
                            .TL.ParallelDistance = .BPoint.Y - LinCalc(.APoint.X, .APoint.Y, .CPoint.X, .CPoint.Y, .BPoint.X)
                            'RemoveObjectFromChart(.BCSwingLine)
                        End With
                    End If
                End If
            End If
        End Sub
        Protected Sub RemoveSwingChannel()
            RemoveObjectFromChart(swingChannel.TL)
            'RemoveObjectFromChart(swingChannel.Parallel)
            RemoveObjectFromChart(swingChannel.BCSwingLine)
            swingChannel.IsActive = False
            swingChannel.IsConfirmed = False
        End Sub

        Private Sub CutChannel(channel As Channel)
            channel.IsCut = True
            If (channel.IsConfirmed And ConfirmedHistoryChannelLinesVisible) Or (channel.IsConfirmed = False And PotentialHistoryChannelLinesVisible) Then
                AddObjectToChart(channel.TL)
            Else
                RemoveObjectFromChart(channel.TL)
            End If

            If channel.IsConfirmed = False Then
                ShowNextBackedUpChannel(channel.Direction, False)
                channel.TL.EndPoint = New Point(channel.CutBarNumber, LinCalc(channel.TL.StartPoint.X, channel.TL.StartPoint.Y, channel.TL.EndPoint.X, channel.TL.EndPoint.Y, channel.CutBarNumber))
                channel.TL.Pen = New Pen(New SolidColorBrush(If(channel.Direction = Direction.Down, PotentialHistoryDownChannelLineColor, PotentialHistoryUpChannelLineColor)), 1)
                channel.TL.ExtendRight = False
            Else
                If HighlightLastCutChannel And channel.IsGapped = False Then
                    If currentPartiallyCutChannel IsNot Nothing Then
                        If currentPartiallyCutChannel.Channel.APoint.X < channel.APoint.X Then
                            FullyCutChannel(currentPartiallyCutChannel.Channel)
                            channel.TL.Pen = New Pen(New SolidColorBrush(If(channel.Direction = Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor)), 1)
                            currentPartiallyCutChannel = New PartiallyCutChannel(channel, swings.Count - 1)
                        Else
                            FullyCutChannel(channel)
                        End If
                    Else
                        channel.TL.Pen = New Pen(New SolidColorBrush(If(channel.Direction = Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor)), 1)
                        currentPartiallyCutChannel = New PartiallyCutChannel(channel, swings.Count - 1)
                    End If
                Else
                    FullyCutChannel(channel)
                End If
            End If
            channel.TL.Pen.DashStyle = TrendLineDashStyle

            If HistoryChannelLineParallelsVisible = False Then channel.TL.HasParallel = False

            'RemoveObjectFromChart(channel.ABSwingLine)
            'RemoveObjectFromChart(channel.BCSwingLine)
            'RemoveObjectFromChart(channel.CDSwingLine)
            RemoveObjectFromChart(channel.BCLengthText)
            RemoveObjectFromChart(channel.TargetText)
            channel.BCLengthText = Nothing
            channel.TargetText = Nothing
        End Sub
        Private Sub FullyCutChannel(channel As Channel)
            ShowNextBackedUpChannel(channel.Direction, True)
            channel.TL.Pen = New Pen(New SolidColorBrush(If(channel.Direction = Direction.Down, ConfirmedHistoryDownChannelLineColor, ConfirmedHistoryUpChannelLineColor)), 1)
            channel.TL.Pen.DashStyle = TrendLineDashStyle
            channel.TL.EndPoint = New Point(channel.CutBarNumber, LinCalc(channel.TL.StartPoint.X, channel.TL.StartPoint.Y, channel.TL.EndPoint.X, channel.TL.EndPoint.Y, channel.CutBarNumber))
            channel.TL.ExtendRight = False
        End Sub

        Private Sub ShowNextBackedUpChannel(direction As Direction, isConfirmed As Boolean)
            If (isConfirmed And ShowOnlyLastConfirmedChannels) Or (isConfirmed = False And ShowOnlyLastPotentialChannels) Then
                'For Each channel In channels
                '    If channel.Direction = direction And channel.IsBackedUp = False And channel.IsCut = False And channel.IsCancelled = False And channel.BCSwingMatched = False And channel.IsConfirmed = isConfirmed And channel.IsGapped = False Then
                '        Exit Sub
                '    End If
                'Next
                Dim c As Channel = Nothing
                For i = channels.Count - 1 To 0 Step -1
                    Dim backup = channels(i)
                    If backup.Direction = direction And backup.IsBackedUp And backup.IsCut = False And backup.IsCancelled = False And backup.IsConfirmed = isConfirmed And backup.IsGapped = False And backup.BCSwingMatched = False Then
                        c = channels(i)
                        Exit For
                    End If
                Next
                If c IsNot Nothing Then
                    If isConfirmed Then
                        c.TL.Pen = New Pen(New SolidColorBrush(If(c.Direction = AutoTrend_old.Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor)), 1)
                        'c.ABSwingLine.Pen = New Pen(New SolidColorBrush(If(c.Direction = AutoTrend_old.Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor)), 2)
                        'c.BCSwingLine.Pen = New Pen(New SolidColorBrush(If(c.Direction = AutoTrend_old.Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor)), 2)
                        'c.CDSwingLine.Pen = New Pen(New SolidColorBrush(If(c.Direction = AutoTrend_old.Direction.Down, ConfirmedDownChannelLineColor, ConfirmedUpChannelLineColor)), 2)
                        'AddObjectToChart(c.ABSwingLine)
                        'AddObjectToChart(c.CDSwingLine)
                        'If c.BCSwingLineRemoved = False And isConfirmed Then AddObjectToChart(c.BCSwingLine)
                        'If BCTargetTextsVisible And c.BCSwingLineRemoved = False Then AddObjectToChart(c.TargetText)
                        'If BCLengthTextsVisible Then AddObjectToChart(c.BCLengthText)
                    Else
                        AddObjectToChart(c.TL)
                    End If
                    c.IsBackedUp = False
                End If
            End If
        End Sub
        Private Sub BackupChannel(channelToShow As Channel)
            If (channelToShow.IsConfirmed And ShowOnlyLastConfirmedChannels) Or (channelToShow.IsConfirmed = False And ShowOnlyLastPotentialChannels) Then
                'Dim firstChannelLocation As Integer
                For Each otherChannel In channels
                    If otherChannel.IsConfirmed = channelToShow.IsConfirmed And otherChannel.IsCut = False And otherChannel.IsCancelled = False And otherChannel.IsGapped = False And otherChannel.Direction = channelToShow.Direction And
                        otherChannel IsNot channelToShow And otherChannel.IsBackedUp = False Then ' AndAlso otherChannel.CPoint.X > channel.CPoint.X AndAlso otherChannel.CPoint.X >= firstChannelLocation
                        channelToShow = otherChannel
                        'firstChannelLocation = otherChannel.CPoint.X
                    End If
                Next
                For Each otherChannel In channels
                    If otherChannel.IsConfirmed = channelToShow.IsConfirmed And otherChannel.IsCut = False And otherChannel.IsCancelled = False And otherChannel.IsGapped = False And otherChannel.Direction = channelToShow.Direction And
                        otherChannel IsNot channelToShow And otherChannel.IsBackedUp = False Then
                        otherChannel.IsBackedUp = True
                        If otherChannel.IsConfirmed Then
                            otherChannel.TL.Pen = New Pen(New SolidColorBrush(If(otherChannel.Direction = Direction.Down, BackedUpConfirmedDownChannelLineColor, BackedUpConfirmedUpChannelLineColor)), 1)
                            otherChannel.BCSwingLine.Pen = New Pen(New SolidColorBrush(If(otherChannel.Direction = Direction.Down, BackedUpConfirmedDownChannelLineColor, BackedUpConfirmedUpChannelLineColor)), 1)
                            'RemoveObjectFromChart(otherChannel.ABSwingLine)
                            'RemoveObjectFromChart(otherChannel.BCSwingLine)
                            'RemoveObjectFromChart(otherChannel.CDSwingLine)
                            'otherChannel.ABSwingLine.Pen = New Pen(New SolidColorBrush(If(otherChannel.Direction = Direction.Down, BackedUpConfirmedDownChannelLineColor, BackedUpConfirmedUpChannelLineColor)), 1)
                            'otherChannel.CDSwingLine.Pen = New Pen(New SolidColorBrush(If(otherChannel.Direction = Direction.Down, BackedUpConfirmedDownChannelLineColor, BackedUpConfirmedUpChannelLineColor)), 1)
                            'RemoveObjectFromChart(otherChannel.TL)

                            'RemoveObjectFromChart(otherChannel.BCLengthText)
                            'RemoveObjectFromChart(otherChannel.TargetText)
                        Else
                            RemoveObjectFromChart(otherChannel.TL)
                        End If
                    End If
                Next
            End If
        End Sub

        Private Function GetAverageSwingAngle() As Double
            Dim swings As List(Of Swing)
            If ChannelMode = ChannelModeType.SetToBase Then
                swings = secondarySwings
            Else
                swings = Me.swings
            End If
            If swings.Count >= 5 Then
                Dim averageCount As Integer = 4
                Dim averageAngleCount As Double = 0
                For i = swings.Count - 1 To swings.Count - averageCount Step -1
                    averageAngleCount += Atan(Abs(swings(i).TL.EndPoint.Y - swings(i).TL.StartPoint.Y) / Abs(swings(i).TL.EndPoint.X - swings(i).TL.StartPoint.X))
                Next
                Return averageAngleCount / averageCount
            Else
                Return 0
            End If
            Return 0
        End Function
        Friend Function GetDollarValue(ByVal priceDif As Decimal) As Decimal
            Dim multiplier As Double
            If Chart.Settings("UseRandom").Value Then
                multiplier = 1
            Else
                If Chart.IB.Contract(Chart.TickerID).Multiplier = "" OrElse Not IsNumeric(Chart.IB.Contract(Chart.TickerID).Multiplier) Then
                    multiplier = 1
                Else
                    multiplier = Chart.IB.Contract(Chart.TickerID).Multiplier
                End If
            End If
            Dim shares As Integer = Chart.Settings("DefaultOrderQuantity").Value
            'Dim a = priceDif / Chart.GetMinTick * Chart.GetMinTick * multiplier * shares
            Return Round(priceDif * multiplier * shares, 2)
        End Function
        Friend Function GetRVFromDollar(ByVal dollarDif As Decimal) As Decimal
            Dim multiplier As Double
            If Chart.Settings("UseRandom").Value Then
                multiplier = 1
            Else
                If Chart.IB.Contract(Chart.TickerID).Multiplier = "" OrElse Not IsNumeric(Chart.IB.Contract(Chart.TickerID).Multiplier) Then
                    multiplier = 1
                Else
                    multiplier = Chart.IB.Contract(Chart.TickerID).Multiplier
                End If
            End If
            Dim shares As Integer = Chart.Settings("DefaultOrderQuantity").Value
            'Dim a = priceDif / Chart.GetMinTick * Chart.GetMinTick * multiplier * shares
            Return Round(dollarDif / (multiplier * shares), 2)
        End Function
        Private Function NewSwing(ByVal color As Color, ByVal startPoint As Point, ByVal endPoint As Point, ByVal show As Boolean, ByVal direction As Direction) As Swing
            Return New Swing(NewTrendLine(color, startPoint, endPoint, show), direction)
        End Function
    End Class

End Namespace
